package mt521.cam.ac.uk;

import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;

public class Graph extends JPanel {
   
    private static final long serialVersionUID = 1L;
    static int[] data = null;
    static int sample = 200;
   
    final int PAD = 20;
   
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        int w = getWidth();
        int h = getHeight();
        // Draw ordinate.
        g2.draw(new Line2D.Double(PAD, PAD, PAD, h-PAD));
        // Draw abcissa.
        g2.draw(new Line2D.Double(PAD, h-PAD, w-PAD, h-PAD));
        double xInc = (double)(w - 2*PAD)/(sample-1);
        double scale = (double)(h - 2*PAD)/getMax();
        // Mark data points.
        g2.setPaint(Color.red);
        double x1 = PAD + 0*xInc;
        double x2 = 0;
        double y1 = PAD + 0*xInc;
        double y2 = 0;
        for(int i = 1; i < sample; i++) {
            x1 = i==1 ? x1 : x2;
            x2 = PAD + i*xInc;
            y1 = i==1 ? y1 : y2;
            y2 = h - PAD - scale*data[i];
            g2.draw(new Line2D.Double(x1, y1, x2, y2));
        }
        //System.out.println("Max value: "+getMax());               //PRINT MAX AMPLITUDE
    }
   
    private int getMax() {
        int max = -Integer.MAX_VALUE;
        for(int i = 0; i < sample; i++) {
            if (data[i] > max) {
                max = data[i];
            }
        }
        return max;
    }
   
    public static void graph(double[] dVals) {
        data = new int[dVals.length];
        for(int i=0; i<dVals.length; i++) {
            data[i] = (int)dVals[i];
        }
        sample=dVals.length;
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(new Graph());
        f.setSize(400,400);
        f.setLocation(200,200);
        f.setVisible(true);
    }
   
}
